package com.itheima.health.resource.poi;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.formula.functions.T;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.awt.*;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class PoiDemo {

    public static void main(String[] args) {

//        readExcel();

        createExcel();

    }

    private static void createExcel() {
        //   代码生成一个excel文档
        XSSFWorkbook workbook = new XSSFWorkbook();
           //  工作簿 创建工作区
        XSSFSheet sheet = workbook.createSheet("黑马程序员");
        //  录入 多行 多单元格数据   List<T>
        XSSFRow row = sheet.createRow(0);
        row.createCell(0).setCellValue("id");
        row.createCell(1).setCellValue("name");
        row.createCell(2).setCellValue("age");

        XSSFRow row1 = sheet.createRow(1);
        row1.createCell(0).setCellValue("001");
        row1.createCell(1).setCellValue("zs");
        row1.createCell(2).setCellValue("20");


        XSSFRow row2 = sheet.createRow(2);
        row2.createCell(0).setCellValue("002");
        row2.createCell(1).setCellValue("lisi");
        row2.createCell(2).setCellValue("22");


        //  workbook.writer 写出输出流  FileOutputStream
        String   fileToBeRead  = "C:/Users/tps52/Desktop/hello1.xlsx";
        try {
            FileOutputStream outputStream = new FileOutputStream(fileToBeRead);
            workbook.write(outputStream);
//            outputStream.flush();
//            outputStream.close();
            System.out.println("文件生成了！");
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    private static void readExcel() {
        //  "C:\\Users\tps52\Desktop\hello.xlsx"

        try {
            String   fileToBeRead  = "C:/Users/tps52/Desktop/hello.xlsx";
            // 创建对Excel工作簿文件的引用
            XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(fileToBeRead));
            // 创建对工作表的引用。
            // 本例是按名引用（让我们假定那张表有着缺省名"Sheet1"）
            XSSFSheet sheet = workbook.getSheet("Sheet1");
//            HSSFSheet sheet = workbook.getSheetAt(0)
            for (Row row : sheet) {
                //  行
                for (Cell cell : row) {
                    //  每一行对应得单元格
                    System.out.print(cell.getStringCellValue()+"\t");
                }
                System.out.println();  //   List<T>
            }
        } catch (Exception e) {
            System.out.println("已运行xlRead() : " + e);
        }


    }


}
